<?php

namespace App\Http\Middleware;

use App\Models\SchoolUser;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CampusAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $school_id =  $request->school_id;
        $campus_id = $request->campus_id;

        if(!$campus_id || $campus_id == 0){
            return resFail(null, "无权限", NOAUTH_CODE);
        }

        $user = SchoolUser::where([
            "school_id" => $school_id,
            "user_id" => Auth::id()
        ])->whereIn('campus_id', [$campus_id, 0])->exists();

        if(!$user){
            return resFail(null, "无权限", NOAUTH_CODE);
        }

        return $next($request);
    }
}
